import json
from django.http import JsonResponse
from django.views import View
from constr_budgets.models import Modules, Project, People
from utils.Infinite import infinite


class Auths(View):
    def post(self, req):
        d = json.loads(req.body)
        return JsonResponse({"code": 200, "msg": "添加成功"})

    def get(self, req):
        d = req.GET.get("template_id")
        if d is not None:
            lis = infinite(list(
                Modules.objects.filter(template_id=d).values("id", "pid", "name", "level", "template", 'is_materials','predict_money','unit','predict_do')))
            return JsonResponse({"code": 200, "msg": "请求成功", "data": lis})
        else:
            lis = infinite(list(Modules.objects.all().values("id", "pid", "name", "level", "template", 'is_materials','predict_money','unit','predict_do')))
            return JsonResponse({"code": 200, "msg": "请求成功", "data": lis})

    def put(self, req):
        d = json.loads(req.body)
        da = list(People.objects.filter(id=d["id"]).values())[0]
        try:
            dic = eval(da["role_auth"])
            dic[d["pro_id"]] = d["modules"]
            People.objects.filter(id=d["id"]).update(role_auth=dic)
            return JsonResponse({"code": 200, "msg": "分配成功"})
        except TypeError:
            ds = {d["pro_id"]: d["modules"]}
            People.objects.filter(id=d["id"]).update(role_auth=ds)
            return JsonResponse({"code": 200, "msg": "分配成功"})

    def delete(self, req):
        return JsonResponse({"code": 200})

    def patch(self, req):
        d = json.loads(req.body)

        print(d, "sssssssssss")
        try:
            d['is_materials']

        except:
            print('非材料')
            try:
                das = list(Project.objects.filter(id=d["pro_id"]).values("templates_id__id"))[0]
                da = list(
                    Modules.objects.filter(template_id=das["templates_id__id"]).values("name", "id", "pid", "level",
                                                                                       'unit'))
                ds = infinite(da)
                return JsonResponse({"code": 200, "data": ds})
            except ValueError:
                return JsonResponse({"code": 200, "msg": "请传入参数"})

        else:
            # if d['is_materials']:
            print('是材料')
            try:
                das = list(Project.objects.filter(id=d["pro_id"]).values("templates_id__id"))[0]

                da = list(
                    Modules.objects.filter(template_id=das["templates_id__id"], is_materials=d['is_materials']).values(
                        "name", "id", "pid", "level"))
                ds = infinite(da)
                return JsonResponse({"code": 200, "data": ds})
            except ValueError:
                return JsonResponse({"code": 200, "msg": "请传入参数"})

        # return JsonResponse({"code": 200, "msg": "请传入参数"})
